﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using Passwords.Biz;
using Silvermoon.Images;

namespace Passwords.Pages
{
    public class LabelTypePickerPage : Page
    {
        private ItemType[] types = new ItemType[] { ItemType.Categories, ItemType.Date, ItemType.Decimal, ItemType.Memo, ItemType.MonthYear, ItemType.NumericPassword, ItemType.Password, ItemType.String, ItemType.Time };
        private ItemType[] orderedTypes;
        private ListView listview;
        private ListViewController<TextItem, ItemType> controller;
        private PasswordLabel label;

        public LabelTypePickerPage()
            : base()
        {
            Styles = StylePool.Metro;
            Styles.SetClass<TextItem>(StylePool.TextItemStyle);
            Title = "CHOOSE LABEL TYPE";
            listview = new ListView { Margin = Margin.Zero };
            Controls.Add(listview);
            controller = new ListViewController<TextItem, ItemType>(listview) { ItemHeight = 80 };
            controller.UpdateItem += new EventHandler<ItemControlGeneratorEventArgs<TextItem>>(controller_UpdateItem);
            controller.InitializeItem += new EventHandler<ItemControlGeneratorEventArgs<TextItem>>(controller_InitializeItem);
            orderedTypes = types.OrderBy(x => x.ToString()).ToArray();
            controller.DataSource = orderedTypes;

        }

        public PasswordLabel Label
        {
            get { return label; }
            set
            {
                label = value;
                OnLabelChanged(value);
            }
        }

        private void OnLabelChanged(PasswordLabel value)
        {
            int index = value != null ? Array.IndexOf<ItemType>(orderedTypes, value.ValueType) : -1;
            listview.SelectedItemIndex = index;
        }

        protected override void OnShown()
        {
            base.OnShown();
            int index = listview.SelectedItemIndex;
            if (index >= 0) listview.BringItemIntoView(index, true);
        }

        void controller_InitializeItem(object sender, ItemControlGeneratorEventArgs<TextItem> e)
        {
            e.Item.Tap += new EventHandler<TapEventArgs>(Item_Tap);
        }

        void Item_Tap(object sender, TapEventArgs e)
        {
            Item item = sender as Item;
            item.IsSelected = true;
            ItemType type = (ItemType)item.DataValue;
            if (label != null)
            {
                label.ValueType = type;
                GoBack();
            }

        }

        void controller_UpdateItem(object sender, ItemControlGeneratorEventArgs<TextItem> e)
        {
            e.Item.Text = e.Value.ToString();
        }

    }
}
